%%Estimate Value-at-Risk using Monte Carlo method
function [var_5] = EstimateVaRMC(number_of_stock, weight , drift, volatility, initial_price, steps)

    local_expected_return = drift/steps;

    price = zeros(steps, 1);
    
    %Run simulation for each stock bases on each stock's assumptions
    for k=1:number_of_stock
        scenario = 1000;
        future_prices(k,:) = zeros(scenario, 1);
        sort_future_prices(k,:) = zeros(scenario, 1);
        %Run scenario 1000 times to get 1000 stock prices at the final step of a stock
     for i = 1:scenario
         randUnif = unifrnd(0, 1, steps, 1);
         norm_inv = norminv(randUnif, 0.0014, volatility(k)*sqrt(1/steps));
         price_increment = norm_inv * initial_price(k);

         %Simulation steps of a stock
         price(1) = initial_price(k) + price_increment(1);
         for j = 2:steps
             price(j) = price(j - 1) + price_increment(j);
         end
         %The price of a stock at final step
         future_prices(k,i) = price(steps);
     end
    %Sort 1000 future stock prices of a stock
     
     %bin_width = 0.736645161290326;
     %nBins = ceil((sort_future_prices(k,scenario) - sort_future_prices(k,1) + 0.00001) / bin_width);
     %frequency = zeros(nBins, 1);
     %cdf_frequency = zeros(nBins, 1);
    
     %id = 1;
     %for i = 1: scenario
      %      while (sort_future_prices(k,i) > (sort_future_prices(k,1) + id * bin_width))
       %         id = id + 1;
        %    end
         %   frequency(id) = frequency(id) + 1;
        
     %end
    
        %for i = 2:nBins
         %cdf_frequency(i) = cdf_frequency(i - 1) + frequency(i);
        %end
    end
    future_prices = future_prices';
    r = future_prices(2:end, :)./future_prices(1:end - 1, :) - 1;
    weight
    %r.'
    portfolio_return = weight*r.';
    sort_portfolio_return = sort(portfolio_return);
    
    var_5 =  quantile(sort_portfolio_return,0.05);
    var_95 = quantile(sort_portfolio_return,0.95);
    %figure;
    %hist(Sort_Future_Prices, nBins);
    %figure;
    %plot(Frequency);
    %figure;
    %plot(cdf_Frequency);
end